import pandas as pd
import numpy as np
from pyecharts import options as opts
from pyecharts.charts import Bar, Timeline
from pyecharts.faker import Faker

class BarChart_flow_month_timeline():
    
    def __init__(self, dataset, place=0):
        self.paint_data=dataset
        self.place=place #九寨沟——0；四姑娘山——1
        self.flow=[];
        
        #主程序入口
        self.main()
    
    #主程序入口函数实现
    def main(self):
        
        # 调用获取数据函数
        self.getData()
        # 调用绘制条形图函数
        self.paintBarChart()
        
    
    #获取数据
    def getData(self):
            
        df=self.paint_data.loc[:,['date','flow']] #取出数据集中的日期和客流数据
        
        df.columns = ['date','flow'] #表头名称

        df['date'] = pd.to_datetime(df['date']) #将数据类型转换为日期类型
        df = df.set_index('date') # 将date设置为index
        self.flow=df       
        self.paint_data=df
        
    
    def paintBarChart(self):
        
        #设置横纵坐标
        months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        
        if self.place==0:
            place='九寨沟'
            years=range(2013, 2017) #设置年份范围
            fileName="1.4 九寨沟2013-2016年月平均客流条形图（含时间轴）.html"
        else:
            place='四姑娘山'
            years=range(2016, 2020) #设置年份范围
            fileName="1.4 四姑娘山2016-2019年月平均客流条形图（含时间轴）.html"
        
        tl = Timeline()
        for i in years:
            weather=self.paint_data[str(i)] #筛选某一年的天气数据
           
            flow_month_nums=[0,0,0,0,0,0,0,0,0,0,0,0,0]
            flow_month_avgs=[0,0,0,0,0,0,0,0,0,0,0,0,0]
            month_daynums = [0,0,0,0,0,0,0,0,0,0,0,0,0]
            
            for j in range(1,13):
                for flowday in weather[str(i)+'-{}'.format(j)].values:
                    flow_month_nums[j]+=flowday
                    month_daynums[j]+=1
                flow_month_nums[j]=int(flow_month_nums[j])
                flow_month_avgs[j]=flow_month_nums[j]/month_daynums[j]

            value=flow_month_avgs[1:13]
            value=np.array(value)
            value=np.round(value,2).tolist()
        
            c = (
                Bar(init_opts=opts.InitOpts(width="900px", height="600px"))
                .add_xaxis(months)
                .add_yaxis("客流", value, color=Faker.rand_color())
                .set_global_opts(
                    title_opts=opts.TitleOpts(title=place+" {} 年月平均客流".format(i)),
                    datazoom_opts=opts.DataZoomOpts(type_="inside"),
                )
            )
            tl.add(c, "{}年".format(i))
        tl.render('resultFile/'+fileName)
        
        print(fileName+"已生成！")
              
